// pages/confirm/confirm.js
import { Product } from '../../model/product.js';
import { Order } from '../../model/order.js';
import { User } from '../../model/user.js';
import { Coupon } from '../../model/coupon.js';
var product = new Product();
var user = new User();
var order = new Order();
var coupon = new Coupon();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    checked: false,
    hidden: false,
    subLoading:  false,
    info:  {},
    userInfo: {},
    num: 1,
    total: 0,
    coupon: [],
    coupon_money: 0,
    coupon_id: 0,
    desc: '',
    team_user_id: '',
    loginshow:true,
    ispaysuccess: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    });
    this.setData({
      team_user_id: options.team_user_id
    });
    this.getProductInfo(options.id);
  },
  /**
   * 获取产品详情
   */
  getProductInfo(id) {
    product.getProductInfo(id,(result)=>{
      this.setData({
        info: result,
        total: result.price
      })
      this.getUserInfo();
    })
  },
  /**
   * 获取用户信息
   */
  getUserInfo() {
    user.getUserInfo((result)=>{
      this.setData({
        userInfo: result,
      })
      this.getCouponList()
    })
  },

  /**
   * 获取可使用优惠券
   */
  getCouponList() {
    coupon.getCouponList(this.data.total,(res)=>{
        this.setData({
          coupon: res,
          hidden: true
        })
        wx.hideLoading();
    })
  },

  openCoupon(){
      this.setData({
        show: true
      })
  },
  onCheckCoupon() {
    this.setData({
      show: false
    })
  },

  /**
   * 修改结算数量
   */
  onChangeNum(e) {
    this.setData({
      num: e.detail,
      total: (e.detail * this.data.info.price) - this.data.coupon_money,
      coupon: []
    })
    this.getCouponList()
  },

  onChangeText(e) {
    this.setData({
      desc: e.detail
    })
  },

  onChangeCoupon(e) {
    let id = e.currentTarget.dataset.id;
    let coupon_money = e.currentTarget.dataset.price;
    let coupon = this.data.coupon
    coupon.forEach((item)=>{
      if(item.id == id) {
        if(item.checked) {
          coupon_money = 0
          id = 0
          item.checked = false
        } else {
          item.checked = true
        }
      } else {
        item.checked = false
      }
    })
    this.setData({
      coupon: coupon,
      coupon_money: coupon_money,
      coupon_id: id,
      total: (this.data.num * this.data.info.price)  - coupon_money
    })
  },


  /**
   * 更新用户信息
   */
  getUserProfile() {
    const self = this
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      lang: 'zh_CN',
      success: (res) => {
        user.updateUser({
          'nickname': res.userInfo.nickName,
          'head_img': res.userInfo.avatarUrl,
          'province': res.userInfo.province,
          'city': res.userInfo.city,
          'gender': res.userInfo.gender
        },(result) => {
          self.getUserInfo()
        })
      }
    })
    
  },

  /**
   * 关闭登录弹窗
   * */
  closeinfo:function(){
    this.setData({
      loginshow:true
    })
  },

  /**
   * 关闭提交之后提醒
   * @param  e 
   */
  hideModal:function(){
    this.setData({
      ispaysuccess:false
    })
  },

  /**
  * 获取手机号
  */
  getPhone: function (e) {
    var that = this;
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      user.phonePost({ encrypted_data: e.detail.encryptedData, iv: e.detail.iv }, (isVild, result) => {
        if (isVild) {
          that.setData({
            loginshow:true
          })
          this.getUserInfo()
        } else {
          wx.showToast({
            title: '获取手机号失败,请稍后重试!',
            icon: 'none',
            duration: 2000
          })
          return false;
        }
      })
    } else {
      wx.showToast({
        title: '请允许获取您的手机号',
        icon: 'none',
        duration: 2000
      })
    }
  },


  onSubmit() {

    var that = this;
    if(!that.data.userInfo.phone){
        that.setData({
          loginshow:false
        })
    }else{
      this.setData({
        subLoading: true
      })
      order.createProductOrder({
        product_id: this.data.info.id,
        number: this.data.num,
        total: this.data.total,
        remark: this.data.desc,
        coupon_id: this.data.coupon_id,
        team_user_id: this.data.team_user_id,
      },(isVild,res)=>{
        if (!isVild) {
          this.setData({
            subLoading: false
          })
          for (var tmp in res.msg) {
            wx.showToast({
              title: res.msg[tmp],
              icon: 'none',
              duration: 2000
            })
            return false
          }
        }else{
            this.goPay(res)
        }
      })
    }
  },
  goPay(res){
    var self = this
    order.preOrder({ out_trade_no:res.result.out_trade_no ,payment: 1}, (isVild,preData)=>{
      if (!isVild) {
        self.setData({
          subLoading: false
        })
        for (var tmp in preData.msg) {
            wx.showToast({
              title: preData.msg[tmp],
              icon: 'none',
              duration: 2000
            })
            return false
          }
        }else{
        if(preData.pay_type == 2){
          wx.hideLoading();
          self.setData({
            subLoading: false
          });
          wx.showModal({
            title: '温馨提示',
            content: '支付成功',
            showCancel: false,
            confirmText: '知道了',
            confirmColor: '#F3474E',
            success:function(res){
              if (res.confirm){
                wx.switchTab({
                  url: '/pages/order/order',
                })
              }
            }
          })
        }else{
          wx.requestPayment({
            timeStamp: preData.timeStamp.toString(),
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function (res) {
              wx.hideLoading();
              self.setData({
                subLoading: false
              });
              wx.showModal({
                title: '温馨提示',
                content: '支付成功',
                showCancel: false,
                confirmText: '知道了',
                confirmColor: '#F3474E',
                success:function(res){
                  if (res.confirm){
                    self.setData({
                      ispaysuccess:true
                    })
                  }
                }
              })
            },
            fail: function (error) {
              console.log(error)
              wx.hideLoading();
              self.setData({
                subLoading: false
              });
              if (error.errMsg == "requestPayment:fail cancel") {
                wx.showToast({
                  title: '取消了支付',
                  icon: 'none',
                  duration: 2000
                })
                return false
              } else {
                wx.hideLoading();
                self.setData({
                  subLoading: false
                });
                wx.showToast({
                  title: '支付错误',
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          })
        }
        }
    })
  },
  toorder:function(){
    wx.switchTab({
      url: '/pages/order/order',
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    var that = this;
    // 设置转发内容
    var shareObj = {
      title:that.data.info.name,
      path: 'pages/product/product?scene=user-' + this.data.userInfo.id+"pid="+this.data.id, // 默认是当前页面，必须是以‘/’开头的完整路径
      imageUrl:that.data.info.img.url,
      success: function (res) {　 // 转发成功之后的回调　　　　　
        if (res.errMsg == 'shareAppMessage:ok') {
        }
      },
      fail: function () {　// 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调（转发成不成功都会执行）
      }
    };
    // 来自页面内的按钮的转发
    if (options.from == 'text') {
      // 此处可以修改 shareObj 中的内容
      shareObj.path ='pages/product/product?scene=user-' + this.data.userInfo.id+"pid="+this.data.id;
    }
    console.log(shareObj);
    // 返回shareObj
    return shareObj;
  }
})
